import platform from '../../config/platform';
import PDDApi from '../../api/PDD';
import BaseMall, { IQueryDetailParams, IQueryListParams } from './BaseMall';
import { GoodsDetail } from './typing/Mall';
import md5 = require('md5');

export default class PDDMall extends BaseMall {
  private clientId = platform.pdd.clientId;
  private clientSecret = platform.pdd.clientSecret;
  private pid = platform.pdd.pid;

  queryList(params: IQueryListParams<any>): Promise<GoodsDetail[]> {
    const queryParams: any = {
      ...this.genCommonParams(),
      type: 'pdd.ddk.goods.search',
      pid: this.pid,
      custom_parameters: '{"uid":"11111","sid":"22222","new":1}',
      keyword: params.searchContent,
      page: params.page,
      page_size: params.pageSize >= 10 ? params.pageSize : 10,
    };
    queryParams.sign = this.genSignature(queryParams);

    return PDDApi.getInstance().search(queryParams) as any;
  }
  queryDetail(params: IQueryDetailParams): Promise<GoodsDetail> {
    void params;
    throw new Error('Method not implemented.');
  }

  private genCommonParams() {
    return {
      client_id: this.clientId,
      timestamp: Date.now().toString().slice(0, 10),
    };
  }

  private genSignature(params) {
    const paramsStr = Object.keys(params).sort().reduce((prev, key) => (prev += `${key}${params[key]}`), '');
    const signStr = `${this.clientSecret}${paramsStr}${this.clientSecret}`;

    return md5(signStr).toUpperCase();
  }
}
